package com.adgox.tiantianbiting.home.search;

import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.adapter.HistoryAdapter;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.HistoryBean;
import com.adgox.tiantianbiting.bean.PageBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.adgox.tiantianbiting.utils.DialogUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SearchActivity extends AppCompatActivity {

    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.rv_result)
    RecyclerView rvResult;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;

    private int currentPage = 1 ;
    private int maxPage = 10 ;
    private int totalPages;
    private HistoryAdapter adapter;
    private String key;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY == (v.getChildAt(0).getMeasuredHeight()) - v.getMeasuredHeight()) {
                    //加载更多
                    if (currentPage < totalPages) {
                        currentPage++;
                        showLoading();
                        getSearchData();
                    } else {
                        Toast.makeText(SearchActivity.this, "没有更多了", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @OnClick(R.id.img_finish)
    public void onFinishClicked() {
        finish();
    }

    @OnClick(R.id.tv_search)
    public void onSearchClicked() {
        if (adapter != null) adapter.clear();
        currentPage = 1;
        key = etSearch.getText().toString().trim();
        getSearchData();
    }

    private void getSearchData() {
        if (key == null||key.length() == 0){
            Toast.makeText(this, "搜索关键字不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        showLoading();
        OkGo.<BaseResponseBean<List<HistoryBean>>>get(ApiConstant.BASE_URL+ApiConstant.SEARCH)
                .params("condition",key)
                .params("userId", ((UserInfo) SessionManager.getDefault().getUser()).getId())
                .params("startPoint",currentPage)
                .params("maxPage",maxPage)
                .execute(new JsonCallback<BaseResponseBean<List<HistoryBean>>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<List<HistoryBean>>> response) {
                        DialogUtils.dismiss();
                        if (!"0".equals(response.body().getCode())){
                            onGetSearchResultFailed(response.body().getMessage());
                            return;
                        }
                        onSetSearchResult(response.body().getData());

                    }
                });
    }

    private void onSetSearchResult(List<HistoryBean> data) {
        if (data == null || data.size() == 0){
            Toast.makeText(this, "获取搜索结果失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if (adapter == null) {
            LinearLayoutManager manager = new LinearLayoutManager(this);
            manager.setSmoothScrollbarEnabled(true);
            manager.setAutoMeasureEnabled(true);

            rvResult.setLayoutManager(manager);
            rvResult.setHasFixedSize(true);
            rvResult.setNestedScrollingEnabled(false);
            adapter = new HistoryAdapter(data);
            rvResult.setAdapter(adapter);
        } else {
            adapter.addDatas(data);
            adapter.notifyDataSetChanged();
        }
    }

    private void showLoading() {
        DialogUtils.showLoadingDialog(this);
    }

    private void onGetSearchResultFailed(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}
